<template>
  <div class="resource-container">
    <div class="search-bar" style="padding: 8px;">
      <el-button type="info" size="large" circle @click="openUploadDialog">
        <el-icon color="yellow" size="18">
          <Sunrise />
        </el-icon>
      </el-button>
      <el-input v-model="searchQuery" style="margin-top: 8px;" placeholder="搜索资料名称或简介" clearable @clear="handleSearch"
        @keyup.enter="handleSearch">
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <search />
            </el-icon>
          </el-button>
        </template>
      </el-input>
    </div>

    <div class="tag-container">
      <el-tag v-for="tag in tags" :key="tag.value" :type="selectedTags.includes(tag.value) ? 'success' : 'info'"
        @click="toggleTag(tag.value)" class="tag-item">
        {{ tag.label }}
      </el-tag>
    </div>

    <!-- 资料列表 -->
    <el-table :data="resources" style="width: 100%" border stripe>
      <el-table-column prop="name" label="资料名称" width="180" sortable />
      <el-table-column prop="materialType" label="资料类型" width="120"/>
      <el-table-column prop="description" label="简介" />
      <el-table-column prop="fileSize" label="文件大小" width="120">
        <template #default="{ row }">
          {{ formatFileSize(row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="downloadCount" label="下载次数" width="120" sortable />
      <el-table-column prop="uploadTime" label="上传时间" width="180" sortable />
      <el-table-column label="操作" width="120">
      <template #default="{ row }">
        <a :href="row.filePath" style="display: inline-flex; align-items: center; gap: 4px;">
            <el-icon><Download /></el-icon> 下载
          </a>
      </template>
</el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" :total="totalResources" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>

  <!-- 上传弹窗 -->
  <el-dialog v-model="uploadDialogVisible" title="上传资料" width="500px">
    <el-form :model="uploadForm" label-width="100px">
      <el-form-item label="资料类型" required>
        <!-- 修改radio组件，使用value替代label -->
        <el-radio-group v-model="uploadForm.materialType">
          <el-radio v-for="tag in tags" :key="tag.value" :value="tag.value">
            {{ tag.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 新增描述输入框 -->
      <el-form-item label="资料描述">
        <el-input 
          v-model="uploadForm.description" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入资料描述"
        />
      </el-form-item>
      <el-upload action="#" :auto-upload="false" :limit="1" :on-change="handleFileChange">
        <el-button type="primary">选择文件</el-button>
      </el-upload>
    </el-form>

    <template #footer>
      <el-button @click="uploadDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitUpload">上传</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Sunrise, Download } from '@element-plus/icons-vue'  // 新增Upload图标
import { ElMessage, type UploadFile } from 'element-plus'
import http from '@/utils/http'

// 搜索相关
const searchQuery = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalResources = ref(0)

const resources = ref([])

// 添加文件大小格式化方法
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取资料列表
const fetchResources = async () => {
  try {
    const res = await http.get('/resource/search/', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: searchQuery.value,
        material_type: selectedTags.value.join(',')
      }
    })

    resources.value = res.data.items.map((item: any) => ({
      id: item.id,
      name: item.name,
      description: item.description,
      fileSize: item.file_size,
      downloadCount: item.download_count,
      uploadTime: item.upload_time,
      materialType: item.material_type,
      filePath: item.download_url
    }))
    totalResources.value = res.data.total
  } catch (error) {
    ElMessage.error('获取资料列表失败')
  }
}

// 修改标签切换方法
const toggleTag = (tagValue: string) => {
  const index = selectedTags.value.indexOf(tagValue)
  if (index === -1) {
    selectedTags.value.push(tagValue)
  } else {
    selectedTags.value.splice(index, 1)
  }
  // 标签变更后重新搜索
  currentPage.value = 1
  fetchResources()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchResources()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchResources()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchResources()
}

onMounted(() => {
  fetchResources()
})

const tags = ref([
  { label: '学习笔记', value: 'notes' },
  { label: '视频课程', value: 'video' },
  { label: '历年真题', value: 'past_paper' },
  { label: '招生简介', value: 'admission' },
  { label: '考试大纲', value: 'syllabus' }
])

const selectedTags = ref<string[]>([])
// 上传相关状态
const uploadDialogVisible = ref(false)
// 修改上传表单
const uploadForm = reactive({
  materialType: '', // 单选资料类型
  description: '',  // 新增描述字段
  file: null as File | null, // 文件对象
})

// 修改提交上传方法
const submitUpload = async () => {
  if (!uploadForm.materialType) {
    ElMessage.warning('请选择资料类型')
    return
  }

  if (!uploadForm.file) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', uploadForm.file)
    formData.append('material_type', uploadForm.materialType)
    formData.append('description', uploadForm.description)
    await http.post('/resource/upload/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    fetchResources() // 刷新列表
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 文件选择处理
const handleFileChange = (uploadFile: UploadFile) => {
  if (uploadFile.raw) {
    // 添加文件大小检查
    const maxSize = 100 * 1024 * 1024 // 100MB
    if (uploadFile.raw.size > maxSize) {
      ElMessage.error('文件大小不能超过100MB')
      uploadForm.file = null
      return
    }
    uploadForm.file = uploadFile.raw as File
  } else {
    uploadForm.file = null
    ElMessage.warning('未选择有效的文件')
  }
}
// 打开上传弹窗
const openUploadDialog = () => {
  uploadForm.materialType = ''
  uploadForm.file = null
  uploadDialogVisible.value = true
}



</script>

<style scoped>
/* 修改页面容器样式 */
.page {
  width: 100%;
  min-height: 100vh;
  /* 使用视口高度 */
  background: #f5f7fa;
  padding: 0;
  margin: 0;
}

/* 修改资源容器样式 */
.resource-container {
  width: 1200px;
  min-height: calc(100vh - 40px);
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 20px auto;
  box-sizing: border-box;
}

/* 调整表格样式 */
.el-table {
  flex: 1;
  width: calc(100% - 40px);
  /* 减去左右边距 */
  margin: 0 auto;
  /* 居中显示 */
  background: transparent;
  table-layout: fixed;
  /* 固定表格布局 */
}

/* 调整表格列样式 */
.el-table-column {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination {
  margin: 20px 0;
  display: flex;
  justify-content: center;
  padding-bottom: 20px;
}

/* 修改后的标签容器样式 */
.tag-container {
  display: flex;
  gap: 10px;
  margin: 15px 20px;
  /* 添加上下边距 */
  padding: 10px 0;
  /* 增加内边距 */
  justify-content: flex-start;
  /* 左对齐 */
  flex-wrap: wrap;
}

.tag-item {
  cursor: pointer;
  padding: 0 15px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.2s;
  margin-right: 8px;
  /* 添加右边距 */
}

.tag-item:hover {
  transform: translateY(-2px);
  /* 添加悬停效果 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
</style>
